package com.fintech.pangu.rocketmq.core.producer.hook;

import com.alibaba.rocketmq.client.hook.SendMessageContext;
import com.alibaba.rocketmq.client.hook.SendMessageHook;
import com.fintech.pangu.rocketmq.metrics.NoOpRocketMQMetricsCollector;
import com.fintech.pangu.rocketmq.metrics.RocketMQMetricConstants;
import com.fintech.pangu.rocketmq.metrics.RocketMQMetricsCollector;
import com.fintech.pangu.rocketmq.metrics.RocketMQSendMessageContext;
import lombok.Setter;

/**
 * 用于收集Metrics指标的SendMessageHook
 */
@Setter
public class SendMessageMetricHookImpl implements SendMessageHook {

    /**
     * Metric指标收集器
     */
    private RocketMQMetricsCollector rocketMQMetricsCollector;

    /**
     * 获取RocketMQMetricsCollector收集器，默认创建NoOpRocketMQMetricsCollector
     * @return
     */
    private RocketMQMetricsCollector getRocketMQMetricsCollector() {
        if(rocketMQMetricsCollector == null){
            synchronized (this){
                if(rocketMQMetricsCollector == null){
                    rocketMQMetricsCollector = new NoOpRocketMQMetricsCollector();
                }
            }
        }

        return rocketMQMetricsCollector;
    }

    @Override
    public String hookName() {
        return "SendMessageMetricsHook";
    }

    @Override
    public void sendMessageBefore(SendMessageContext context) {
        // nothing to do
    }

    @Override
    public void sendMessageAfter(SendMessageContext sendMessageContext) {
        // 如果不存在异常信息，内部发送失败
        if(sendMessageContext.getException() != null){
            // 通过SendMessageContext构造RocketMQSendMessageContext
            RocketMQSendMessageContext context = new RocketMQSendMessageContext(sendMessageContext);
            context.setSendStatus(RocketMQMetricConstants.SendStatus.SEND_FAILED);  // 个性化新增状态

            // 调用Collector记录内部发送失败
            getRocketMQMetricsCollector().sendKernelFailure(context);
        }
        // 如果存在SendResult，内部发送成功
        else if(sendMessageContext.getSendResult() != null){
            // 通过SendMessageContext构造RocketMQSendMessageContext
            RocketMQSendMessageContext context = new RocketMQSendMessageContext(sendMessageContext);

            // 调用Collector记录内部发送成功
            getRocketMQMetricsCollector().sendKernelSuccess(context);
        }
    }

}
